﻿<%@ WebHandler Language="C#" Class="RBStepParameterMaintPageHandler" %>

using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using System.Collections.Generic;
using System.Collections;
using Newtonsoft.Json;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using System.Collections;

//Description:工步排产参数维护
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:zhunan
//create Date:2024-7-17
public class RBStepParameterMaintPageHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    uLMSCommonBusiness commonBusiness = new uLMSCommonBusiness();
    WorkShiftBusiness workshiftBusiness = new WorkShiftBusiness();
    LimitedCapacityBusiness limitBusiness = new LimitedCapacityBusiness();//排产类
    string factoryid = System.Configuration.ConfigurationManager.AppSettings["RBFactoryID"];
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "getStepData":
                    getStepData(context);
                    break;
                case "getStepInfoData":
                    getStepInfoData(context);
                    break;
                case "updateStepInfo":
                    updateStepInfo(context);
                    break;
                case "getStepResources":
                    getStepResources(context);
                    break;
                case "addStepResources":
                    addStepResources(context);
                    break;
                case "removeStepResources":
                    removeStepResources(context);
                    break;
                case "getFactoryResources":
                    getFactoryResources(context);
                    break;
                case "getStepCheckPoints":
                    getStepCheckPoints(context);
                    break;
                case "getStepTools":
                    getStepTools(context);
                    break;
                case "getStepAuxs":
                    getStepAuxs(context);
                    break;
                case "saveChargingQty":
                    saveChargingQty(context);
                    break;
                case "batchUpdateStepInfo":
                    BatchUpdateStepInfo(context);
                    break;
                case "updateWorkflowTemp":
                    updateWorkflowTemp(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    public void getStepData(HttpContext context)
    {
        string sql = @"
SELECT DECODE(s.iskey,1,'是','否') iskey,
       wt.workflowstepid, wt.workflowstepname, wt.sequence,wt.description,wt.islaststep,DECODE(wt.wipmsglabel,NULL,'Spec','SubWorkflow') wfstype,wt.controlcode,
       s.specrevision,s.iscooperation,s.isspotcheck,s.lastcheck,s.specid,sb.specname,s.parentspecno,s.commonsubworkflow,s.opdesc,
       b.bomid,wc.workcentername,t.teamname,
       NVL(s.specno,SUBSTR(wt.workflowstepname,0,INSTR(wt.workflowstepname,'-','1')-1)) specno,
       NVL(wf2.workflowid,wf.workflowid) workflowid,
       NVL( wf2.workflowbaseid,wf.workflowbaseid) workflowbaseid,
       NVL(wf2.workflowrevision,wf.workflowrevision) workflowrevision,
       NVL( wb2.workflowname,wb.workflowname) workflowname,
       wtt.workflowtype,wtt.process_no,wtt.ly2sequence,
       e.fullname,e.employeename,f.factoryid,f.factoryname,ct.lastchangedate,NVL2(pb.productname,pb.productname||':'||p.productrevision,NULL) defaultproduct,
       wff.image       
FROM workflowstep wt
LEFT JOIN specbase sb_ ON sb_.specbaseid = NVL(wt.specbaseid, wt.subworkflowbaseid)
LEFT JOIN spec s ON s.specid = NVL(sb_.revofrcdid,wt.specid)
LEFT JOIN specbase sb ON sb.specbaseid = s.specbaseid
--正常子工艺
LEFT JOIN v_steprelevanttosonwf sbsk ON sbsk.workflowstepid = wt.workflowstepid 
LEFT JOIN workflow wf ON wf.workflowid = sbsk.sonworkflowid
LEFT JOIN workflowbase wb ON wb.workflowbaseid = wf.workflowbaseid
--通用子工艺的情况
LEFT JOIN workflowbase wb2 ON wb2.workflowname='WF-'||s.commonsubworkflow
LEFT JOIN workflow wf2 ON wf2.process_no=s.commonsubworkflow AND wf2.workflowid=wb2.revofrcdid
LEFT JOIN bom b ON b.workflowid = wf.workflowid
LEFT JOIN workcenter wc ON wc.workcenterid = wt.workcenterid
LEFT JOIN team t ON t.teamid = wt.teamid
LEFT JOIN workflow wtt ON wtt.workflowid = wt.workflowid --工艺
LEFT JOIN employee e ON wf.zgemployeeid=e.employeeid
LEFT JOIN factory f ON f.factoryid = wtt.factoryid
LEFT JOIN changestatus ct ON ct.parentid = wtt.workflowid
LEFT JOIN product p ON p.productid= wtt.productid
LEFT JOIN productbase pb ON pb.productbaseid=p.productbaseid
LEFT JOIN workflow wff ON wff.workflowid = wt.workflowid
WHERE wt.sequence IS NOT NULL AND wt.workflowid= '{0}'
ORDER BY wt.sequence";
        sql = string.Format(sql, context.Request.Form["workflowid"].ToString());
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql);
        dt.Columns.Add("ChildWorkflow");
        foreach (DataRow dr in dt.Rows)
        {
            if (dr["WFSTYPE"].ToString() == "SubWorkflow")
            {
                if (dr["WORKFLOWNAME"].ToString() == "")
                {
                    dr["ChildWorkflow"] = "子工艺";
                }
                dr["ChildWorkflow"] = dr["WORKFLOWNAME"].ToString() + ":" + dr["WORKFLOWREVISION"].ToString();
                if (dr["commonsubworkflow"].ToString() != "")
                {
                    dr["ChildWorkflow"] = dr["ChildWorkflow"].ToString() + "|通用";
                }
            }
        }
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = dt.Rows.Count;
        r.status = new Result.Meta(200, "请求成功");
        context.Response.ContentType = "text/html";
        context.Response.Write(JsonConvert.SerializeObject(r));
    }

    void getStepInfoData(HttpContext context)
    {
        string sql = @"
SELECT sf.workflowstepid,sf.stepinfoid,sf.stepno,sf.description stepdesc,sfb.stepinfoname,sf.workcenterid,wc.workcentername,sf.teamid,t.teamname,
       sf.steptype,sf.preparecycle,sf.makecycle,sf.shipcycle,sf.transfercycle,sf.chargingqty,m.specialcoursespecreportno,
       listagg(rdd.resourcename,'、') WITHIN GROUP (ORDER BY rdd.resourcename) stepresourcelist
FROM stepinfo sf
LEFT JOIN stepinfobase sfb ON sfb.stepinfobaseid = sf.stepinfobaseid
LEFT JOIN stepresourceinfo sri ON sri.stepid = sf.stepinfoid
LEFT JOIN resourcedef rdd ON rdd.resourceid = sri.resourceid
LEFT JOIN Workcenter wc ON wc.workcenterid = sf.workcenterid
LEFT JOIN team t ON t.teamid = sf.teamid
LEFT JOIN workflowstep ws ON ws.workflowstepid = sf.workflowstepid
LEFT JOIN (
    SELECT r.specialcoursespecreportno,t.workflowstepid
    FROM SpecialCourseSpecMapp t
    INNER JOIN SpecialCourseSpecReport r ON r.specialcoursespecreportid = t.specialcoursespecreportid
    WHERE t.workflowstepid = '{0}'
) m ON m.workflowstepid = sf.workflowstepid
WHERE sf.workflowstepid = '{0}'
GROUP BY sf.workflowstepid,sf.stepinfoid,sf.stepno,sf.description,sfb.stepinfoname,sf.workcenterid,wc.workcentername,sf.teamid,t.teamname,
         sf.steptype,sf.preparecycle,sf.makecycle,sf.shipcycle,sf.transfercycle,sf.chargingqty,m.specialcoursespecreportno";
        sql = string.Format(sql, context.Request.Form["workflowstepid"].ToString());
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = dt.Rows.Count;
        r.status = new Result.Meta(200, "请求成功");
        context.Response.ContentType = "text/html";
        context.Response.Write(JsonConvert.SerializeObject(r));
    }

    void updateStepInfo(HttpContext context)
    {
        string updateSql = @"
UPDATE stepinfo t 
SET t.preparecycle = '{0}',t.makecycle = '{1}',t.transfercycle = '{2}',t.shipcycle = '{3}',t.chargingqty = '{4}',t.workcenterid = '{5}',t.teamid = '{6}'
WHERE t.stepinfoid = '{7}'";
        string stepinfoid = context.Request.Form["stepinfoid"].ToString();
        string preparecycle = context.Request.Form["preparecycle"].ToString();
        string makecycle = context.Request.Form["makecycle"].ToString();
        string transfercycle = context.Request.Form["transfercycle"].ToString();
        string shipcycle = context.Request.Form["shipcycle"].ToString();
        string chargingqty = context.Request.Form["chargingqty"].ToString();
        string workcenterID = context.Request.Form["workcenterid"].ToString();
        string teamID = context.Request.Form["teamid"].ToString();
        updateSql = string.Format(updateSql, preparecycle, makecycle, transfercycle, shipcycle, chargingqty, workcenterID, teamID, stepinfoid);
        int rows = DatabaseHelper.ExecuteSql(updateSql);
        Result r = new Result();
        r.data = stepinfoid;
        r.total = rows;
        r.status = new Result.Meta(200, "请求成功");
        context.Response.ContentType = "text/html";
        context.Response.Write(JsonConvert.SerializeObject(r));
    }

    /// <summary>
    /// 批量更新工步信息（目前只更新工区班组） add by zhangrj 20241126
    /// </summary>
    /// <param name="context"></param>
    void BatchUpdateStepInfo(HttpContext context)
    {
        string updateSql = @"UPDATE stepinfo s SET s.workcenterid = '{0}',s.teamid = '{1}' WHERE s.workflowstepid = '{2}'";
        string workflowstepid = context.Request.Form["workflowstepid"].ToString();
        string workcenterID = context.Request.Form["workcenterid"].ToString();
        string teamID = context.Request.Form["teamid"].ToString();
        updateSql = string.Format(updateSql, workcenterID, teamID, workflowstepid);
        int rows = DatabaseHelper.ExecuteSql(updateSql);
        Result r = new Result();
        r.data = workflowstepid;
        r.total = rows;
        r.status = new Result.Meta(200, "请求成功");
        context.Response.ContentType = "text/html";
        context.Response.Write(JsonConvert.SerializeObject(r));
    }

    void getStepResources(HttpContext context)
    {
        string sql = @"
SELECT t.stepid stepinfoid,rd.resourceid,rd.resourcename,rd.description resourcedesc,NVL(pr.chargingqty,'') chargingqty,pr.id,pr.productname
FROM stepresourceinfo t
LEFT JOIN resourcedef rd ON rd.resourceid = t.resourceid
LEFT JOIN productresourcechargingqtyinfo pr ON pr.resourceid = rd.resourceid AND pr.productname = '{0}'
WHERE t.stepid = '{1}'";
        sql = string.Format(sql, context.Request.Form["productname"].ToString(), context.Request.Form["stepinfoid"].ToString());
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = dt.Rows.Count;
        r.status = new Result.Meta(200, "请求成功");
        context.Response.ContentType = "text/html";
        context.Response.Write(JsonConvert.SerializeObject(r));
    }

    // 工步添加设备
    void addStepResources(HttpContext context)
    {
        var dtPostData = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["postData"].ToString());
        ArrayList sqlList = new ArrayList();
        foreach (DataRow dr in dtPostData.Rows)
        {
            string insertSql = "INSERT INTO stepresourceinfo(resourceid,stepid,stepresourceinfoid) VALUES('{0}','{1}','{2}')";
            insertSql = string.Format(insertSql, dr["resourceid"].ToString(), dr["stepinfoid"].ToString(), Guid.NewGuid().ToString());
            sqlList.Add(insertSql);
        }
        Boolean isSuccess = DatabaseHelper.ExecuteSqlListTran(sqlList);
        Result r = new Result();
        r.data = isSuccess;
        r.total = dtPostData.Rows.Count;
        r.status = new Result.Meta(200, "请求成功");
        context.Response.ContentType = "text/html";
        context.Response.Write(JsonConvert.SerializeObject(r));
    }

    // 工步移除设备
    void removeStepResources(HttpContext context)
    {
        var dtPostData = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["postData"].ToString());
        ArrayList sqlList = new ArrayList();
        foreach (DataRow dr in dtPostData.Rows)
        {
            string deleteSql = "DELETE stepresourceinfo t WHERE t.resourceid = '{0}' AND t.stepid = '{1}'";
            deleteSql = string.Format(deleteSql, dr["resourceid"].ToString(), dr["stepinfoid"].ToString());
            sqlList.Add(deleteSql);
        }
        Boolean isSuccess = DatabaseHelper.ExecuteSqlListTran(sqlList);
        Result r = new Result();
        r.data = isSuccess;
        r.total = dtPostData.Rows.Count;
        r.status = new Result.Meta(200, "请求成功");
        context.Response.ContentType = "text/html";
        context.Response.Write(JsonConvert.SerializeObject(r));
    }

    void getFactoryResources(HttpContext context)
    {
        string sql = @"
SELECT rd.resourceid,rd.resourcename,rd.description resourcedesc
FROM resourcedef rd
WHERE rd.factoryid = '{0}'";
        sql = string.Format(sql, factoryid);
        if (context.Request.Form["resourcename"].ToString().Trim() != "")
        {
            sql += string.Format(" AND rd.resourcename LIKE '%{0}%'", context.Request.Form["resourcename"].ToString().Trim());
        }
        if (context.Request.Form["resourcedesc"].ToString().Trim() != "")
        {
            sql += string.Format(" AND rd.description LIKE '%{0}%'", context.Request.Form["resourcedesc"].ToString().Trim());
        }
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = dt.Rows.Count;
        r.status = new Result.Meta(200, "请求成功");
        context.Response.ContentType = "text/html";
        context.Response.Write(JsonConvert.SerializeObject(r));
    }

    void getStepCheckPoints(HttpContext context)
    {
        string sql = @"
SELECT sc.stepcheckpointid,sc.stepinfoid,wfs.workflowstepid,wfs.workflowid,
       so.stepno,so.description stepdesc,sob.stepinfoname,
       so.steptype,sc.checkno,sc.name,sc.checkpointnotedis,sc.drawingrequiredis,
       DECODE(sc.keycheck,1,'是','否') keycheck,
       DECODE(sc.qualitycheck,1,'是','否') qualitycheck
FROM stepcheckpoint sc
INNER JOIN workflowstep wfs ON sc.workflowstepid=wfs.workflowstepid
LEFT JOIN stepinfo so ON so.workflowstepid = sc.workflowstepid AND so.stepinfoid=sc.stepinfoid  
LEFT JOIN stepinfobase sob ON so.stepinfobaseid = sob.stepinfobaseid
LEFT JOIN spectype st ON st.spectypeid = so.spectypeid
LEFT JOIN stepcheckpointresult scr ON scr.stepcheckpointid=sc.stepcheckpointid
WHERE sc.stepinfoid = '{0}'";
        sql = string.Format(sql, context.Request.Form["stepinfoid"].ToString());
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = dt.Rows.Count;
        r.status = new Result.Meta(200, "请求成功");
        context.Response.ContentType = "text/html";
        context.Response.Write(JsonConvert.SerializeObject(r));
    }

    void getStepTools(HttpContext context)
    {
        string sql = @"
SELECT st.stepinfoid,sit.stepno,sit.description stepdesc,t.description tooldesc,t.toolname,t.drawingno,t.tooltype,rt.resourcetypename
FROM stepinfotools st
LEFT JOIN stepinfo sit ON sit.stepinfoid = st.stepinfoid
LEFT JOIN stepinfobase sb ON sb.stepinfobaseid = sit.stepinfobaseid
INNER JOIN
(
  SELECT specialtoolname toolname,DESCRIPTION,specialtoolid toolid,resourcetypeid,drawingno,'夹模具' tooltype FROM specialtool
  UNION ALL
  SELECT mtt.measuretoolname toolname,mtt.description,mtt.measuretoolid toolid,mtt.resourcetypeid,mtt.drawingno,'量具' tooltype FROM measuretool mtt
  UNION ALL 
  SELECT ctt.cuttoolname toolname,ctt.description,ctt.cuttoolid toolid,ctt.resourcetypeid,ctt.drawingno,'刀具' tooltype FROM cuttool ctt
) t ON st.tools = t.toolid
LEFT JOIN resourcetype rt  ON rt.resourcetypeid = t.resourcetypeid
WHERE st.stepinfoid = '{0}'";
        sql = string.Format(sql, context.Request.Form["stepinfoid"].ToString());
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = dt.Rows.Count;
        r.status = new Result.Meta(200, "请求成功");
        context.Response.ContentType = "text/html";
        context.Response.Write(JsonConvert.SerializeObject(r));
    }

    void getStepAuxs(HttpContext context)
    {
        string sql = @"
SELECT st.stepinfoid,sit.stepno,sit.description stepdesc,
       aux.description tooldesc,
       aux.auxmaterialname toolname,
       aux.vendormodel drawingno,
       '辅材' tooltype,
       rt.resourcetypename
FROM stepinfotools st
LEFT JOIN stepinfo sit ON sit.stepinfoid = st.stepinfoid
LEFT JOIN stepinfobase sb ON sb.stepinfobaseid = sit.stepinfobaseid
INNER JOIN auxmaterial aux ON aux.auxmaterialid = st.tools
LEFT JOIN resourcetype rt  ON rt.resourcetypeid = aux.resourcetypeid
WHERE st.stepinfoid = '{0}'";
        sql = string.Format(sql, context.Request.Form["stepinfoid"].ToString());
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = dt.Rows.Count;
        r.status = new Result.Meta(200, "请求成功");
        context.Response.ContentType = "text/html";
        context.Response.Write(JsonConvert.SerializeObject(r));
    }

    //更新装炉槽量
    void saveChargingQty(HttpContext context)
    {
        var dtPostData = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["postData"].ToString());
        ArrayList sqlList = new ArrayList();
        foreach (DataRow dr in dtPostData.Rows)
        {
            string resourceid = dr["resourceid"].ToString();
            string productname = dr["productname"].ToString();
            string employeeid = m_UserInfo.EmployeeID == null ? "" : m_UserInfo.EmployeeID;
            string chargingqty = dr["chargingqty"].ToString().Trim() == "" ? "0" : dr["chargingqty"].ToString().Trim();

            string sql = @"SELECT * FROM productresourcechargingqtyinfo t WHERE t.resourceid = '{0}' AND t.productname = '{1}'";
            sql = string.Format(sql, resourceid, productname);
            DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql);
            if (dt.Rows.Count > 0)
            {
                string updateSql = @"
UPDATE productresourcechargingqtyinfo t 
SET t.chargingqty = '{0}',t.lastchangedate = sysdate,t.lastchangeemployee = '{1}'
WHERE t.resourceid = '{2}' AND t.productname = '{3}'";
                updateSql = string.Format(updateSql, chargingqty, employeeid, resourceid, productname);
                sqlList.Add(updateSql);
            }
            else
            {
                string id = Guid.NewGuid().ToString();
                string insertSql = @"
INSERT INTO productresourcechargingqtyinfo(chargingqty,createdate,createemployee,id,productname,resourceid)
VALUES('{0}',sysdate,'{1}','{2}','{3}','{4}')";
                insertSql = string.Format(insertSql, chargingqty, employeeid, id, productname, resourceid);
                sqlList.Add(insertSql);
            }
        }
        Boolean isSuccess = DatabaseHelper.ExecuteSqlListTran(sqlList);
        Result r = new Result();
        r.data = isSuccess;
        r.total = dtPostData.Rows.Count;
        r.status = new Result.Meta(200, "请求成功");
        context.Response.ContentType = "text/html";
        context.Response.Write(JsonConvert.SerializeObject(r));
    }

    void updateWorkflowTemp(HttpContext context)
    {
        string sql = string.Format("UPDATE workflow wf SET wf.image = '{0}' WHERE wf.workflowid = '{1}'",
            context.Request.Form["image"].ToString(),
            context.Request.Form["workflowid"].ToString());
        int count = DatabaseHelper.ExecuteSql(sql);
        Result r = new Result();
        r.data = null;
        r.total = count;
        r.status = new Result.Meta(200, "请求成功");
        context.Response.ContentType = "text/html";
        context.Response.Write(JsonConvert.SerializeObject(r));
    }
}